/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
$(function () {
    $("#buttonAdd").click(function () {
        var type = $("#selectType"),
                num = 0,
                isEventRight = false,
                isEventLeft = false,
                isEventMax = false,
                isEventBoth = false;

        blockAllEditable();

        if ($(".section").length !== 0) {
            var max = 0;
            for (var i = 0; i < $(".section").length; i++) {
                var num = (parseInt($(".section").get(i).getAttribute("name"), 10) || 0) + 1;
                if (num > (max || 0))
                    max = num;
            }
            num = max;
        }

        var sectionBox = document.createElement("section");
        sectionBox.setAttribute("class", "section");
        sectionBox.setAttribute("name", num);
        sectionBox.setAttribute("id", "section" + num);

        var divUpButton = document.createElement("div");
        divUpButton.setAttribute("class", "up");
        sectionBox.appendChild(divUpButton);

        var divDownButton = document.createElement("div");
        divDownButton.setAttribute("class", "down");
        sectionBox.appendChild(divDownButton);

        var divDeleteButton = document.createElement("div");
        divDeleteButton.setAttribute("class", "delete");
        divDeleteButton.className = divDeleteButton.className + " shadow";
        divDeleteButton.innerHTML = "X";
        sectionBox.appendChild(divDeleteButton);

        if (type.val() === '1') {
            var divText = document.createElement("div");
            divText.setAttribute("class", "text hasmenu");
            divText.setAttribute("contenteditable", "true");
            divText.setAttribute("spellcheck", "true");
            divText.innerHTML = "Write something here...";
            sectionBox.appendChild(divText);
        } else if (type.val() === '2') {
            var divImg = document.createElement("div");
            divImg.setAttribute("class", "img");
            var divImageUpload = document.createElement("div");
            divImageUpload.setAttribute("class", "image-upload");
            divImg.appendChild(divImageUpload);

            var divYoutubeUpload = document.createElement("div");
            divYoutubeUpload.setAttribute("class", "youtube-upload");
            divImg.appendChild(divYoutubeUpload);
            sectionBox.appendChild(divImg);

            var inputFile = document.createElement("input");
            inputFile.setAttribute("type", "file");
            inputFile.setAttribute("style", "display:none;");
            sectionBox.appendChild(inputFile);

            isEventMax = true;
        } else if (type.val() === '3') {
            var divImg = document.createElement("div");
            divImg.setAttribute("class", "img");
            divImg.className = divImg.className + " img-left";
            var divImageUpload = document.createElement("div");
            divImageUpload.setAttribute("class", "image-upload");
            divImg.appendChild(divImageUpload);

            var divYoutubeUpload = document.createElement("div");
            divYoutubeUpload.setAttribute("class", "youtube-upload");
            divImg.appendChild(divYoutubeUpload);
            sectionBox.appendChild(divImg);

            var divText = document.createElement("div");
            divText.setAttribute("class", "text");
            divText.setAttribute("contenteditable", "true");
            divText.innerHTML = "Write something here...";
            sectionBox.appendChild(divText);

            var inputFile = document.createElement("input");
            inputFile.setAttribute("type", "file");
            inputFile.setAttribute("style", "display:none;");
            sectionBox.appendChild(inputFile);

            isEventLeft = true;
        } else if (type.val() === '4') {
            var divImg = document.createElement("div");
            divImg.setAttribute("class", "img");
            divImg.className = divImg.className + " img-right";
            var divImageUpload = document.createElement("div");
            divImageUpload.setAttribute("class", "image-upload");
            divImg.appendChild(divImageUpload);

            var divYoutubeUpload = document.createElement("div");
            divYoutubeUpload.setAttribute("class", "youtube-upload");
            divImg.appendChild(divYoutubeUpload);
            sectionBox.appendChild(divImg);

            var divText = document.createElement("div");
            divText.setAttribute("class", "text");
            divText.setAttribute("contenteditable", "true");
            divText.innerHTML = "Write something here...";
            sectionBox.appendChild(divText);

            var inputFile = document.createElement("input");
            inputFile.setAttribute("type", "file");
            inputFile.setAttribute("style", "display:none;");
            sectionBox.appendChild(inputFile);

            isEventRight = true;
        } else if (type.val() === '5') {
            var divImg1 = document.createElement("div");
            divImg1.setAttribute("id", "img1");
            divImg1.setAttribute("class", "img");
            divImg1.className = divImg1.className + " img-left img-both";
            var divImageUpload1 = document.createElement("div");
            divImageUpload1.setAttribute("class", "image-upload");
            divImg1.appendChild(divImageUpload1);

            var divYoutubeUpload1 = document.createElement("div");
            divYoutubeUpload1.setAttribute("class", "youtube-upload");
            divImg1.appendChild(divYoutubeUpload1);
            sectionBox.appendChild(divImg1);

            var divImg2 = document.createElement("div");
            divImg2.setAttribute("id", "img2");
            divImg2.setAttribute("class", "img");
            divImg2.className = divImg2.className + " img-right img-both";
            var divImageUpload2 = document.createElement("div");
            divImageUpload2.setAttribute("class", "image-upload");
            divImg2.appendChild(divImageUpload2);

            var divYoutubeUpload2 = document.createElement("div");
            divYoutubeUpload2.setAttribute("class", "youtube-upload");
            divImg2.appendChild(divYoutubeUpload2);
            sectionBox.appendChild(divImg2);

            var inputFile1 = document.createElement("input");
            inputFile1.setAttribute("id", "file1");
            inputFile1.setAttribute("type", "file");
            inputFile1.setAttribute("style", "display:none;");
            sectionBox.appendChild(inputFile1);

            var inputFile2 = document.createElement("input");
            inputFile2.setAttribute("id", "file2");
            inputFile2.setAttribute("type", "file");
            inputFile2.setAttribute("style", "display:none;");
            sectionBox.appendChild(inputFile2);

            isEventBoth = true;
        }

        var divEndOfSection = document.createElement("div");
        divEndOfSection.setAttribute("class", "end-of-section");
        sectionBox.appendChild(divEndOfSection);

        $(".content-box").find("article")[0].appendChild(sectionBox);

        initialEventToElement("#section" + num,
                isEventLeft,
                isEventRight,
                isEventMax,
                isEventBoth);

        $(window).scrollTop($("#section" + num).offset().top);
    });

    $(document).on('paste', '[contenteditable]', function (e) {
        var text = (e.originalEvent || e).clipboardData.getData('text/plain') || prompt('Paste something..');
        window.document.execCommand('insertText', false, text);
        e.preventDefault();
    });

    var saveContent = "";
    $("#buttonPreview").clickToggle(
            function () {
                $("#buttonAdd").attr("disabled", "disabled");
                $("#buttonAdd").css("cursor", "not-allowed");
                $("#buttonReset").attr("disabled", "disabled");
                $("#buttonReset").css("cursor", "not-allowed");
                $(this).html("Back");
                saveContent = $(".content-box").find("article").html();
                $(".content-box").find("article").html(generateContent());
            },
            function () {
                $("#buttonAdd").removeAttr("disabled");
                $("#buttonAdd").css("cursor", "pointer");
                $("#buttonReset").removeAttr("disabled");
                $("#buttonReset").css("cursor", "pointer");
                $(this).html("Preview");
                $(".content-box").find("article").html(saveContent);
                for (var i = 0; i < $(".section").length; i++) {
                    var id = $(".section")[i].getAttribute("id"),
                            el = $('#' + id),
                            isEventLeft = false,
                            isEventRight = false,
                            isEventMax = false,
                            isEventBoth = false;
                    if (el.find(".img").length) {
                        if (el.find(".img").attr("id")) {
                            isEventBoth = true;
                        } else {
                            if (el.find(".img").attr("class").indexOf("left") !== -1) {
                                isEventLeft = true;
                            } else if (el.find(".img").attr("class").indexOf("right") !== -1) {
                                isEventRight = true;
                            } else {
                                isEventMax = true;
                            }
                        }
                    }
//                    alert("left: " + isEventLeft + ", right: " + isEventRight + ", max: " + isEventMax + ", both: " + isEventBoth);
                    initialEventToElement('#' + id,
                            isEventLeft,
                            isEventRight,
                            isEventMax,
                            isEventBoth);
                }
            }
    );

    $(".top-box").click(function () {
        $(window).scrollTop(0);
    });

    $(".bottom-box").click(function () {
        $(window).scrollTop($(document).height());
    });

    $("section").on("click", ".section", function (e) {
        $(this).height("auto");
        $(this).css("height", "auto");
        $("#sortable").sortable("disable");
        $("#sortable").enableSelection();
        var nowId = $(this).attr("id");
        blockEditableById(nowId);
        e.stopPropagation();
    });

    $("section").on("blur", ".section", function () {
        if ($(this).find(".img").height() > $(this).find(".text").height()) {
            $(this).find(".img").height($(this).find(".text").height());
        }
        $(this).height("auto");
        $(this).css("height", "auto");
    });

    $(window).click(function () {
        $("#sortable").sortable("enable");
        $("#sortable").disableSelection();
        blockAllEditable();
    });

    var globaScrollHeight = 0,
            isHoldScroll = false;
    $(window).scroll(function () {
        var scrollHeight = $(window).scrollTop();

        if (isHoldScroll) {
            $(this).scrollTop(globaScrollHeight);
            return;
        }

        if ($("html").height() < $(window).height()) {
            $(".bottom-box").css("display", "none");
            $(".bottom-box").css("top", 0);
            $(".bottom-box").css("bottom", 0);
            $(".top-box").css("display", "none");
            $(".top-box").css("top", 0);
            $(".top-box").css("bottom", "0");
        } else {
            if (scrollHeight > $(window).height() / 2) {
                $(".top-box").css("display", "block");
                $(".top-box").css("top", scrollHeight + $(window).height() - 60);
                $(".top-box").css("bottom", null);

                $(".bottom-box").css("display", "none");
                $(".bottom-box").css("bottom", "0");
            } else {
                $(".bottom-box").css("display", "block");
                $(".bottom-box").css("top", scrollHeight + $(window).height() - 60);
                $(".bottom-box").css("bottom", null);

                $(".top-box").css("display", "none");
                $(".top-box").css("bottom", "0");
            }

            var trueDivHeight = $('html')[0].scrollHeight;
            var divHeight = $(window).height();
            var maxHeightScroll = trueDivHeight - divHeight;
            if (scrollHeight === maxHeightScroll) {
                $(".bottom-box").css("display", "none");
                $(".bottom-box").css("top", 0);
                $(".bottom-box").css("bottom", 0);
            }
        }
    });

    $('section').on("change", "input[type=file]", function () {
        var input = $(this);
        var sourceFile = $(this).val();
        var parent = $(this).parent();
        var target = $(this).parent().find(".img");
        if (input[0].files && input[0].files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                if (input.attr("id")) {
                    var numImg = input.attr("id").substring(input.attr("id").length - 1);
                    parent.find("#img" + numImg).find("img").remove();
                    parent.find("#img" + numImg).find("iframe").remove();
                    var divImg = document.createElement("img");
                    divImg.setAttribute("src", e.target.result);
                    divImg.setAttribute("alt", sourceFile);
                    parent.find("#img" + numImg)[0].appendChild(divImg);
                } else {
                    target.find("img").remove();
                    target.find("iframe").remove();
                    var divImg = document.createElement("img");
                    divImg.setAttribute("src", e.target.result);
                    divImg.setAttribute("alt", sourceFile);
                    target[0].appendChild(divImg);
                }
            };

            reader.readAsDataURL(input[0].files[0]);
        }
    });

    function blockEditableById(nowId) {
        blockAllEditable();
        $("#" + nowId).removeClass("block");
        $("#" + nowId).find(".up").css("display", "block");
        $("#" + nowId).find(".down").css("display", "block");
    }

    function blockAllEditable() {
        for (var i = 0; i < $(".section").length; i++) {
            var id = $(".section")[i].getAttribute("id");
            $("#" + id).addClass("block");
            $("#" + id).find(".up").css("display", "none");
            $("#" + id).find(".down").css("display", "none");
        }
    }

    function initialEventToElement(section,
            isEventLeft,
            isEventRight,
            isEventMax,
            isEventBoth) {

        $(section).find(".text").ckeditor();

        if (isEventRight || isEventLeft || isEventMax) {
            $(section).find(".img").hover(
                    function () {
                        $(section).find(".img").find(".image-upload").css("display", "block");
                        $(section).find(".img").find(".youtube-upload").css("display", "block");
                    },
                    function () {
                        $(section).find(".img").find(".image-upload").css("display", "none");
                        $(section).find(".img").find(".youtube-upload").css("display", "none");
                    }
            );
            $(section).find(".img").find(".image-upload").click(function () {
                $(section).find("input[type=file]").click();
            });
            $(section).find(".img").find(".youtube-upload").click(function () {
                var dialog = $("#youtube-form").dialog({
                    autoOpen: true,
                    height: 180,
                    width: 500,
                    modal: true,
                    buttons: {
                        "Submit": function () {
                            dialog.dialog("close");
                            $(section).find(".img").find("iframe").remove();
                            $(section).find(".img").find("img").remove();
                            if ($("#youtube-link").val()
                                    && $("#youtube-link").val().split("/")) {
                                var sourceArr = $("#youtube-link").val().split("/");
                                var source = sourceArr[sourceArr.length - 1].replace("watch?v=", "");
                                if (source.split("&").length > 1) {
                                    source = source.split("&")[0];
                                }
                                $(section).find(".img").append('<iframe src="//www.youtube.com/embed/' + source + '" frameborder="0" allowfullscreen></iframe>');
                            }
                        },
                        Cancel: function () {
                            dialog.dialog("close");
                        }
                    }
                });
            });
        }
        if (isEventLeft) {
            $(section).find(".img").find(".ui-resizable-handle").remove();
            $(section).find(".img").resizable({
                handles: 's, e, se',
                resize: function (event, ui) {
                    $(this).resizable("option", "minHeight", 200);
                    $(this).resizable("option", "minWidth", 200);
                    $(this).resizable("option", "maxHeight", 600);
                    $(this).resizable("option", "maxWidth", 700);
                    ui.position.left = ui.originalPosition.left;
                    ui.size.width = (ui.size.width
                            - ui.originalSize.width) + ui.originalSize.width;

                    if ($(section).find(".text").height() < $(this).height() + 50) {
                        $(this).height(200);
                    }
                    $(section).height($(section).find(".text").height());
                }
            });
        } else if (isEventRight) {
            $(section).find(".img").find(".ui-resizable-handle").remove();
            $(section).find(".img").resizable({
                handles: 's, w, sw',
                resize: function (event, ui) {
                    $(this).resizable("option", "minHeight", 200);
                    $(this).resizable("option", "minWidth", 200);
                    $(this).resizable("option", "maxHeight", 600);
                    $(this).resizable("option", "maxWidth", 700);
                    ui.position.left = ui.originalPosition.left;
                    ui.size.width = (ui.size.width
                            - ui.originalSize.width) + ui.originalSize.width;

                    if ($(section).find(".text").height() < $(this).height() + 50) {
                        $(this).height(200);
                    }
                    $(section).height($(section).find(".text").height());
                }
            });
        } else if (isEventMax) {
            $(section).find(".img").find(".ui-resizable-handle").remove();
            $(section).find(".img").resizable({
                handles: 's',
                resize: function (event, ui) {
                    $(this).resizable("option", "minHeight", 200);
                    $(this).resizable("option", "maxHeight", 450);
                    ui.position.left = ui.originalPosition.left;
                    ui.size.width = (ui.size.width
                            - ui.originalSize.width) + ui.originalSize.width;
                }
            });
        } else if (isEventBoth) {
            $(section).find("#img1").find(".ui-resizable-handle").remove();
            $(section).find("#img1").resizable({
                handles: 's, e',
                resize: function (event, ui) {
                    $(this).resizable("option", "minHeight", 200);
                    $(this).resizable("option", "maxHeight", 450);
                    $(this).resizable("option", "minWidth", 300);
                    $(this).resizable("option", "maxWidth", 700);

                    if (ui.originalSize.width !== ui.size.width) {
                        //element has been resized horizontally
                        $(this).next().width($(".content-box").find("article").width() - $(this).width() - 10);
                        var img1Width = $(this).width() / $(section).width() * 100,
                                img2Width = $(this).next().width() / $(section).width() * 100;
                        console.log(img1Width);
                        $(this).width(Math.floor(img1Width) + "%");
                        $(this).next().width(Math.floor(img2Width) + "%");
                    }
                    if (ui.originalSize.height !== ui.size.height) {
                        //element has been resized vertically
                        $(this).next().height($(this).height());
                    }

                    ui.position.left = ui.originalPosition.left;
                    ui.size.width = (ui.size.width
                            - ui.originalSize.width) + ui.originalSize.width;
                }
            });
            $(section).find("#img2").find(".ui-resizable-handle").remove();
            $(section).find("#img2").resizable({
                handles: 's',
                resize: function (event, ui) {
                    $(this).resizable("option", "minHeight", 200);
                    $(this).resizable("option", "maxHeight", 450);
                    $(this).resizable("option", "minWidth", 300);
                    $(this).resizable("option", "maxWidth", 700);

                    //element has been resized vertically
                    $(this).prev().height($(this).height());

                    ui.position.left = ui.originalPosition.left;
                    ui.size.width = (ui.size.width
                            - ui.originalSize.width) + ui.originalSize.width;
                }
            });

            $(section).find("#img1").hover(
                    function () {
                        $(section).find("#img1").find(".image-upload").css("display", "block");
                        $(section).find("#img1").find(".youtube-upload").css("display", "block");
                    },
                    function () {
                        $(section).find("#img1").find(".image-upload").css("display", "none");
                        $(section).find("#img1").find(".youtube-upload").css("display", "none");
                    }
            );
            $(section).find("#img2").hover(
                    function () {
                        $(section).find("#img2").find(".image-upload").css("display", "block");
                        $(section).find("#img2").find(".youtube-upload").css("display", "block");
                    },
                    function () {
                        $(section).find("#img2").find(".image-upload").css("display", "none");
                        $(section).find("#img2").find(".youtube-upload").css("display", "none");
                    }
            );

            $(section).find("#img1").find(".image-upload").click(function () {
                $(section).find("#file1").click();
            });
            $(section).find("#img1").find(".youtube-upload").click(function () {
                var dialog = $("#youtube-form").dialog({
                    autoOpen: true,
                    height: 180,
                    width: 500,
                    modal: true,
                    buttons: {
                        "Submit": function () {
                            dialog.dialog("close");
                            $(section).find("#img1").find("iframe").remove();
                            $(section).find("#img1").find("img").remove();
                            if ($("#youtube-link").val()
                                    && $("#youtube-link").val().split("/")) {
                                var sourceArr = $("#youtube-link").val().split("/");
                                var source = sourceArr[sourceArr.length - 1].replace("watch?v=", "");
                                if (source.split("&").length > 1) {
                                    source = source.split("&")[0];
                                }
                                $(section).find("#img1").append('<iframe src="//www.youtube.com/embed/' + source + '" frameborder="0" allowfullscreen></iframe>');
                            }
                        },
                        Cancel: function () {
                            dialog.dialog("close");
                        }
                    }
                });
            });

            $(section).find("#img2").find(".image-upload").click(function () {
                $(section).find("#file2").click();
            });
            $(section).find("#img2").find(".youtube-upload").click(function () {
                var dialog = $("#youtube-form").dialog({
                    autoOpen: true,
                    height: 180,
                    width: 500,
                    modal: true,
                    buttons: {
                        "Submit": function () {
                            dialog.dialog("close");
                            $(section).find("#img2").find("iframe").remove();
                            $(section).find("#img2").find("img").remove();
                            if ($("#youtube-link").val()
                                    && $("#youtube-link").val().split("/")) {
                                var sourceArr = $("#youtube-link").val().split("/");
                                var source = sourceArr[sourceArr.length - 1].replace("watch?v=", "");
                                if (source.split("&").length > 1) {
                                    source = source.split("&")[0];
                                }
                                $(section).find("#img2").append('<iframe src="//www.youtube.com/embed/' + source + '" frameborder="0" allowfullscreen></iframe>');
                            }
                        },
                        Cancel: function () {
                            dialog.dialog("close");
                        }
                    }
                });
            });
        }

        $(section).find(".delete").click(function () {
            openDialog($(section), "Do you want to delete this element?");
        });

        $(section).find(".up").click(function () {
            var current = $(section);
            current.prev().before(current);
            $(window).scrollTop(current.offset().top - ($(window).height() - $(".toolbar").height()));
        });

        $(section).find(".down").click(function () {
            var current = $(section);
            current.next().after(current);
            $(window).scrollTop(current.offset().top - ($(window).height() - $(".toolbar").height()));
        });
    }

    function generateContent() {
        var html = '';
        for (var i = 0; i < $(".section").length; i++) {
            var id = $(".section")[i].getAttribute("id"),
                    el = $('#' + id);
            html += '<section class="section">';
            if (el.find(".img").length
                    && (el.find(".img").find("img").length
                            || el.find(".img").find("iframe").length)) {
                if (el.find(".img").length > 1) {
                    html += '<div class="' + el.find(".img").attr("class") + '" style="' + el.find("#img1").attr("style") + '">';
                    if (el.find("#img1").find("img").attr("src")) {
                        html += '<img src="' + el.find("#img1").find("img").attr("src") + '"/>';
                    }
                    if (el.find("#img1").find("iframe").attr("src")) {
                        html += '<iframe frameborder="0" allowfullscreen src="' + el.find("#img1").find("iframe").attr("src") + '"></iframe>';
                    }
                    html += '</div>';
                    html += '<div class="' + el.find(".img").attr("class") + '" style="' + el.find("#img2").attr("style") + '">';
                    if (el.find("#img2").find("img").attr("src")) {
                        html += '<img src="' + el.find("#img2").find("img").attr("src") + '"/>';
                    }
                    if (el.find("#img2").find("iframe").attr("src")) {
                        html += '<iframe frameborder="0" allowfullscreen src="' + el.find("#img2").find("iframe").attr("src") + '"></iframe>';
                    }
                    html += '</div>';
                } else {
                    var style = " ";
                    if (el.find(".img").attr("style")) {
                        style = el.find(".img").attr("style");
                    }
                    html += '<div class="' + el.find(".img").attr("class") + '" style="' + style + '">';
                    if (el.find(".img").find("img").attr("src")) {
                        html += '<img src="' + el.find(".img").find("img").attr("src") + '">';
                    }
                    if (el.find(".img").find("iframe").attr("src")) {
                        html += '<iframe frameborder="0" allowfullscreen src="' + el.find(".img").find("iframe").attr("src") + '"></iframe>';
                    }
                    html += '</div>';
                }
            }
            if (el.find(".text").length) {
                html += '<div class="' + el.find(".text").attr("class") + '" style="min-height: 0; height:auto;">';
                html += el.find(".text").html();
                html += '</div>';
            }
            html += '<div class="end-of-section"></div>';
            html += '</section>\r\n';
        }

        return html;
    }

    function openDialog(el, msg) {
        isHoldScroll = true;
        globaScrollHeight = $(window).scrollTop();
        $("#dialog").html(msg);

        // Define the Dialog and its properties.
        $("#dialog").dialog({
            resizable: false,
            modal: true,
            title: "Confirm",
            height: 150,
            width: 500,
            buttons: {
                "Yes": function () {
                    isHoldScroll = false;
                    $(this).dialog('close');
                    if (el.is("article")) {
                        el.empty();
                    } else {
                        el.remove();
                    }
                },
                "No": function () {
                    isHoldScroll = false;
                    $(this).dialog('close');
                }
            }
        });
    }

    $("#buttonReset").click(function () {
        openDialog($(".content-box").find("article"), "Do you want to reset a content?");
    });
});

(function ($) {
    $.fn.clickToggle = function (func1, func2) {
        var funcs = [func1, func2];
        this.data('toggleclicked', 0);
        this.click(function () {
            var data = $(this).data();
            var tc = data.toggleclicked;
            $.proxy(funcs[tc], this)();
            data.toggleclicked = (tc + 1) % 2;
        });
        return this;
    };
}(jQuery));